package com.cyou.weplay.db;

import com.cyou.weplay.utils.StringUtils;

import java.sql.Connection;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.DataSourceUtils;

/**
 * TableTemplate
 *
 * @author zhaomingyu
 * @param <R>
 */
public abstract class TableTemplate<R> {

    protected TableShardManager shardManager;

    public TableTemplate(TableShardManager shardManager) {
        this.shardManager = shardManager;
    }

    protected abstract R doWork(Connection conn, String shardedTable, String key) throws Exception;

    public R execute(String tableName, String key) throws Exception {
        TableShardInfo shardInfo = this.shardManager.getShardInfo(tableName, key);
        DataSource ds = shardInfo.getDatasource();
        Connection conn = DataSourceUtils.getConnection(ds);
        String shardedName;
        if (StringUtils.isEmpty(shardInfo.getShardedName())) {
            shardedName = tableName;
        } else {
            shardedName = shardInfo.getShardedName();
        }

        R r = doWork(conn, shardedName, key);
        DataSourceUtils.releaseConnection(conn, ds);
        return r;
    }

    public R execute(String tableName) throws Exception {
        return execute(tableName, "");
    }
}
